<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Login extends CI_Controller {
	public function index()
	{
            if ($this->session->userdata('user_id') != null){
                redirect(base_url());
            }
            $username = "";
            $password = "";
            extract($this->ajax->post("username","password"));
            
            if ($this->input->server('REQUEST_METHOD') == "POST"){
                $this->doLogin($username, $password);

                return;
            }

            $data['title'] = "Login";
            $data['data'] = array (
                "title"=>"Login"
                );

            $data['view'] = "home/view_login";
            //$this->load->view('view_template',$data);
            $this->load->view("home/view_login");
	}
        
        private function doLogin($username, $password){
            
            $this->load->model('staffusers');
            
            $user = $this->staffusers->login($username,encrypt_password($password));
            
            if ($user != null){
                $this->session->set_userdata(array(
                    "logged_in" => TRUE,
                    "username"  => $user->staffuser_login,
                    "name"      => $user->staffuser_title,
                    "email"     => $user->staffuser_email,
                    "role"      => $user->staffuser_role,
                    "user_id"   => $user->staffuser_id,
                ));
                redirect(base_url());
            }
            else{
                $this->session->set_flashdata("error", 'Invalid Username/Password Combination');
                redirect(base_url()."home/login");
            }
            
        }
}